package com.dantfb.util;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/FileUploadHandler")
public class FileUploadHandler extends HttpServlet {
 
   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
	   String uuid = (String)request.getSession().getAttribute("UUID"); 
	   String UPLOAD_DIRECTORY  = (String)request.getServletContext().getRealPath("/")+"images\\profils\\"+uuid;
	   System.out.println(UPLOAD_DIRECTORY);
       if(ServletFileUpload.isMultipartContent(request)){
           try {
               List<FileItem> multiparts = new ServletFileUpload(
                                        new DiskFileItemFactory()).parseRequest(request);
             
               for(FileItem item : multiparts){
                   if(!item.isFormField()){
                       
                       item.write( new File(UPLOAD_DIRECTORY + File.separator + uuid+".jpg"));
                   }
               }
          
              //File uploaded successfully
              request.setAttribute("message", "File Uploaded Successfully");
           } catch (Exception ex) {
              request.setAttribute("message", "File Upload Failed due to " + ex);
              
              response.sendRedirect("home.jsp?notif=IMAGE_NOT_UPLOADED_SUCCESSFULY");
              return;
           }          
        
       }else{
           request.setAttribute("message",
                                "Sorry this Servlet only handles file upload request");
       }
   
       response.sendRedirect("home.jsp?notif=IMAGE_UPLOADED_SUCCESSFULY");
    
   }
 
}

